package org.example.huoshan_translation;

import com.volcengine.model.request.translate.TranslateTextRequest;
import com.volcengine.model.response.translate.TranslateTextResponse;
import com.volcengine.service.translate.ITranslateService;
import com.volcengine.service.translate.impl.TranslateServiceImpl;
import org.example.translation.*;

import java.util.*;

public class HuoshanTranslation extends DefaultLangSupportHandler {

    private String SecretAccessKey;
    private String AccessKeyID;
    private final ITranslateService translateService = TranslateServiceImpl.getInstance();

    public HuoshanTranslation(PropValueSupplier propValueSupplier) {
        super(propValueSupplier);
        SecretAccessKey = propValueSupplier.get("huoshan.secretAccessKey");
        AccessKeyID = propValueSupplier.get("huoshan.accessKeyID");
        translateService.setAccessKey(AccessKeyID);
        translateService.setSecretKey(SecretAccessKey);
    }

    @Override
    public TranslationResponseBean requestTranslation(TranslationPostBean postBean) {
        TranslateTextRequest translateTextRequest = new TranslateTextRequest();
        translateTextRequest.setSourceLanguage(getSupportLang(postBean.getSourceCountry())); // 不设置表示自动检测
        translateTextRequest.setTargetLanguage(getSupportLang(postBean.getTargetCountry()));
        translateTextRequest.setTextList(Collections.singletonList(postBean.getSourceString()));

        try {
            TranslateTextResponse translateText = translateService.translateText(translateTextRequest);
            if (translateText.getResponseMetadata().getError() == null &&
                    !translateText.getTranslationList().isEmpty()) {
                return new TranslationResponseBean()
                        .setTargetResult(translateText.getTranslationList().get(0).getTranslation())
                        .setSourceString(postBean.getSourceString())
                        .setSourceCountry(postBean.getSourceCountry())
                        .setTargetCountry(postBean.getTargetCountry());
            } else {
                requestTranslation(postBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new TranslationResponseBean()
                .setTargetResult("未完成翻译")
                .setSourceString(postBean.getSourceString())
                .setSourceCountry(postBean.getSourceCountry())
                .setTargetCountry(postBean.getTargetCountry());
    }

}
